//元胞自动机生成随机地图


var map = [];
var _w
var _h
var precentWall

/**
 * 操作地形
 * @constructor
 */
function MakeCaverns(_map) {
    // By initilizing column in the outter loop, its only created ONCE
    for (var column = 0, row = 0; row <= _h - 1; row++) {
        for (column = 0; column <= _w - 1; column++) {
            _map[column][row] = PlaceWallLogic(column, row);
        }
    }
}


/**
 * 根据周围墙的数量判断该点是不是可以为墙
 * @param x
 * @param y
 * @return {number} 1墙0可通行
 * @constructor
 */
//修改
function PlaceWallLogic(x, y) {
    var numWalls = GetAdjacentWalls(x, y, 1, 1);
    if (map[x][y] == 1) {
        if (numWalls >= 4) return 1;
    }
    else {
        if (numWalls >= 5) return 1;
    }
    return 0;
}


/**
 * 返回该点附近墙的数目
 * @param x
 * @param y
 * @param scopeX 范围大小
 * @param scopeY 范围大小
 * @return {number}
 * @constructor
 */
function GetAdjacentWalls(x, y, scopeX, scopeY) {
    var startX = x - scopeX;
    var startY = y - scopeY;
    var endX = x + scopeX;
    var endY = y + scopeY;

    var iX = startX;
    var iY = startY;

    var wallCounter = 0;
    for (iY = startY; iY <= endY; iY++) {
        for (iX = startX; iX <= endX; iX++) {
            if (!(iX == x && iY == y)) {
                if (IsWall(iX, iY)) {
                    wallCounter += 1;
                }
            }
        }
    }
    return wallCounter;
}

/**
 * 是否是墙
 * @constructor
 */
//修改
function IsWall(x, y) {
    // Consider out-of-bound a wall
    if (IsOutOfBounds(x, y)) {
        // return true;
        return false;
    }

    if (map[x][y] == 1) {
        return true;
    }

    if (map[x][y] == 0) {
        return false;
    }
    return false;
}

/**
 * 数组越界
 * @constructor
 */
function IsOutOfBounds(x, y) {
    if (x < 0 || y < 0) {
        return true;
    }
    else if (x > _w - 1 || y > _h - 1) {
        return true;
    }
    return false;
}


/**
 * 清空地图
 * @constructor
 */
function Blankmap() {
    for (var column = 0, row = 0; row < _h; row++) {
        for (column = 0; column < _w; column++) {
            map[column][row] = 0;
        }
    }
}

function RandomFillmap() {
    var mapMiddle = 0; // Temp variable
    for (var column = 0, row = 0; row < _h; row++) {
        for (column = 0; column < _w; column++) {
            map[column][row] = RandomPercent(precentWall);
        }
    }
}

function RandomPercent(percent) {
    if (percent >= Math.random() * 100) {
        return 1;
    }
    return 0;
}

function mapHandler(wid, hei, _percentWalls) {
    _w = wid;
    _h = hei;
    precentWall = _percentWalls;
    map = new Array();
    for (var i = 0; i < _w; i++) {
        map[i] = new Array();
        for (var j = 0; j < _h; j++) {
            map[i][j] = 0;
        }
    }
    RandomFillmap();
    return map;
}


